const Router = require('koa-router');
const tool = require("../../tools/tool");
const router = new Router();
const {db, QueryTypes} = require("../../models/db");
const tools = require("../../tools/tool");

// 应收明细
router.post('/list/ysdetail', async ctx => {
    try {
        let user = ctx.user
        let body = ctx.request.body
        let tenantId = user.tenantId;
        let buId = body.formData.buId;
        let salesId = body.formData.salesId;

        let beg = body.formData.beginDate ? body.formData.beginDate : '2001-01-01';
        let end = body.formData.endDate ? body.formData.endDate : tools.getDay()
        let bu = ''
        if(buId) bu = ` and buId=${buId} `
        let contact = `select tenantId, id buId, name buName from contact where tenantId=${tenantId} `
        if(salesId) {
            contact = `select a.tenantId,b.buId,a.name buName from contact a inner join contact_sales b on a.tenantId=b.tenantId and a.id=b.buId and b.salesId=${salesId} and a.tenantId=${tenantId} `
        }
        let lastSql = `
            select init,b.buName, billDate, billNo, transTypeName, totalAmount, billType, ysAdd, yusAdd, a.tenantId, a.buId, jy, a.remark,otherType, transType from
                (
                    select 0 id, 1 init,'' billDate,'' billNo,'期初' transTypeName,0 totalAmount,'QC' billType,0 ysAdd,0 yusAdd, tenantId,buId, jy, '' remark,'' otherType,0 transType from
                        (
                            select tenantId,buId,sum(jy) as jy from v_invoice_dz_ys
                            where tenantId = ${tenantId} ${bu} and billType <>'SR' and billDate < '${beg}'
                            group by tenantId,buId
                        ) a
                    union all
                    select id, init, billDate, billNo, transTypeName, totalAmount, billType,
                           case when billType='YS2YS' then -totalAmount else ysAdd end ysAdd,
                           case when billType='YS2YS' then -totalAmount else yusAdd end yusAdd,
                           tenantId, buId, jy, remark,otherType,b.transType from
                        (
                            select id, 0 init,billDate,billNo,transTypeName,transType,
                                   totalAmount,otherType,billType,
                                   case
                                       when billType in('YSK','YSG') then 0
                                       when billType in('RECEIPT') then -(isnull(rpAmount,0)+isnull(skYh,0))
                                       else (isnull(totalAmount,0)-isnull(disAmount,0)-isnull(rpAmount,0)) end ysAdd,
                                   case when billType in('YSK','YSG') then rpAmount else 0 end yusAdd,
                                   tenantId,buId ,0 jy ,remark
                            from v_invoice_dz_ys
                            where tenantId = ${tenantId} ${bu}  and billType <>'SR'
                                  and billDate >= '${beg}' and billDate<='${end}'
                        ) b
                ) a inner join (${contact}) b on a.buId=b.buId and a.tenantId=b.tenantId
           

        `
        lastSql += '  order by buId,billDate,id '
        let list = await db.query(lastSql, {type: QueryTypes.SELECT})
        let ret = []
        for (let i = 0; i < list.length; i++) {
            if(i === 0) {
                if(list[i].transTypeName !== '期初') {
                    ret.push({buName: list[i].buName, transTypeName: '期初',jy: '', buId: list[i].buId})
                }
                ret.push(list[i])
            }
            else {
                if(list[i].buId !== list[i-1].buId) {
                    // 加小计
                    ret.push({
                        buName: list[i-1].buName,
                        transTypeName: '小计',
                        jy: '',
                        buId: list[i-1].buId
                    })
                    if(list[i].transTypeName !== '期初') {
                        ret.push({buName: list[i].buName, transTypeName: '期初',jy: '', buId: list[i].buId})
                    }
                    ret.push(list[i])
                }
                else {
                    ret.push(list[i])
                }
            }
        }
        if(ret.length > 0) {
            ret.push({
                buName: list[list.length-1].buName,
                transTypeName: '小计',
                jy: '',
                buId: list[list.length-1].buId
            })
            for (let i = 0; i < ret.length; i++) {
                if(i > 0) {
                    if(ret[i].buId === ret[i-1].buId) {
                        ret[i].jy = tool.minus(tool.add(ret[i-1].jy,ret[i].ysAdd), ret[i].yusAdd)
                        ret[i].buName = ''
                    }
                }
            }
            ret.map(row => {
                if(tool.xe.toNumber(row.ysAdd) ===0) row.ysAdd = ''
                if(tool.xe.toNumber(row.yusAdd) ===0) row.yusAdd = ''
            })
        }
        return ctx.suc('', {
            total: 0,
            list: ret
        })
    }
    catch (e) {

        return ctx.err(e);
    }
})



module.exports = router;